package com.lyeducation.services.course;

import com.lyeducation.controllers.dto.ChapterDTO;
import com.lyeducation.controllers.dto.ChapterInfoIndexDTO;
import com.lyeducation.core.course.ChapterService;
import com.lyeducation.entities.course.ChapterEntity;
import com.lyeducation.entities.course.CourseEntity;
import com.lyeducation.entities.course.VideoAccessRoleEnum;
import com.lyeducation.entities.course.VideoEntity;
import com.lyeducation.entities.course.middle.ChapterVideoEntity;
import com.lyeducation.entities.course.middle.CourseChapterEntity;
import com.lyeducation.entities.order.OrderMaster;
import com.lyeducation.enums.PayStatusEnum;
import com.lyeducation.enums.ResultEnum;
import com.lyeducation.exception.LeadingEagleException;
import com.lyeducation.repository.ChapterRepository;
import com.lyeducation.repository.CourseRepository;
import com.lyeducation.repository.OrderDetailRepository;
import com.lyeducation.repository.OrderMasterRepository;
import com.lyeducation.security.config.SecurityPrincipalContext;
import com.lyeducation.services.base.BaseServiceImpl;
import com.lyeducation.util.KeyUtil;
import com.lyeducation.util.StringUtils;
import com.lyeducation.util.controllerUtil.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.transform.Transformers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ChapterServieImpl extends BaseServiceImpl<ChapterEntity> implements ChapterService {
    @Autowired
    private ChapterRepository chapterRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Override
    public JsonResult delChapter(String chapterId) {

        List<ChapterVideoEntity> chapterVideoEntities =
                chapterRepository.findByFiled(ChapterVideoEntity.class, "chapterId", chapterId);
        Map paramMap = new HashMap();
        List<String> ids = new ArrayList<>(chapterVideoEntities.size());
        for (int i = 0; i < chapterVideoEntities.size(); i++) {
            ids.add(chapterVideoEntities.get(i).getVideoId());
        }
        paramMap.put("ids", ids);
        String hql = "as v set v.isDelete=true where v.id in:ids";
        chapterRepository.updateFileds(VideoEntity.class, hql, paramMap, null);
        if (!chapterRepository.softDeleteById(chapterId)) {
            return JsonResult.putFail("没有该章节或已被删除");
        }
        return JsonResult.putSuccess();
    }

    @Override
    public ChapterDTO addChapter(ChapterDTO chapterDTO) {
        if (StringUtils.isNotBlank(chapterDTO.getChapterName())) {
            if (StringUtils.trimToNull(chapterDTO.getId()) != null) {
                throw new LeadingEagleException(ResultEnum.PARAM_ERROR);
            } else {
                String chapterId = KeyUtil.genUniqueKey();
                chapterDTO.setId(chapterId);
                ChapterEntity chapterEntity = new ChapterEntity();
                BeanUtils.copyProperties(chapterDTO, chapterEntity);
                // 保存到chapter表
                chapterEntity = chapterRepository.save(chapterEntity);

                // 保存到course_chapter表
                CourseChapterEntity courseChapterEntity = new CourseChapterEntity();
                courseChapterEntity.setCourseId(chapterDTO.getCourseId());
                courseChapterEntity.setChapterId(chapterEntity.getId());
                chapterRepository.save(courseChapterEntity);

                // 返回实体
                BeanUtils.copyProperties(chapterEntity, chapterDTO);
                return chapterDTO;
            }
        }
        return null;
    }

    @Override
    public ChapterInfoIndexDTO chapterInfoIndex(String openid, String chapterId) {
        if (StringUtils.isNotBlank(chapterId)) {
            //获取章节详情
            ChapterEntity chapterEntity = chapterRepository.findById(chapterId);
            //查询中间表拿到课程id
            List<CourseChapterEntity> courseChapterEntity = chapterRepository.findByFiled(CourseChapterEntity.class, "chapterId", chapterEntity.getId());
            //获取课程详情
            CourseEntity courseEntity = courseRepository.findById(courseChapterEntity.get(0).getCourseId());

            ChapterInfoIndexDTO chapterInfoIndexDTO = new ChapterInfoIndexDTO();

            //判断课程是否为vip课程并查询该openid是否有订单
            if (String.valueOf(VideoAccessRoleEnum.vipPly.getValue()).equals(String.valueOf(courseEntity.getVideoAccessRoleEnum())) && orderMasterRepository.existsByBuyerOpenid(openid)) {
                //查出该用户的所有订单
                List<OrderMaster> orderMasterList = orderMasterRepository.findByBuyerOpenid(openid);
                for (int i = 0; i < orderMasterList.size(); i++) {
                    //判断订单是否为支付成功的订单并判断该openid和课程是否在订单详情表
                    if (PayStatusEnum.SUCCESS.getCode().equals(orderMasterList.get(i).getPayStatus()) && orderDetailRepository.existsByCourseIdAndOrderId(courseEntity.getId(), orderMasterList.get(i).getOrderId())) {
                        //把视频列表装进章节详情
                        chapterEntity.setVideoEntityList(videoEntityList(chapterId));
                        BeanUtils.copyProperties(chapterEntity, chapterInfoIndexDTO);
                    }
                }
            } else if (String.valueOf(VideoAccessRoleEnum.user.getValue()).equals(String.valueOf(courseEntity.getVideoAccessRoleEnum())) && openid.equals(SecurityPrincipalContext.getUserDetailsImpl().getId())) {
                //TODO 需要把用户id改成openid
                //把视频列表装进章节详情
                chapterEntity.setVideoEntityList(videoEntityList(chapterId));
                BeanUtils.copyProperties(chapterEntity, chapterInfoIndexDTO);
            } else if (String.valueOf(VideoAccessRoleEnum.share.getValue()).equals(String.valueOf(courseEntity.getVideoAccessRoleEnum()))) {
                //把视频列表装进章节详情
                chapterEntity.setVideoEntityList(videoEntityList(chapterId));
                BeanUtils.copyProperties(chapterEntity, chapterInfoIndexDTO);
            } else {
                BeanUtils.copyProperties(chapterEntity, chapterInfoIndexDTO);
                chapterInfoIndexDTO.setTips("需要登录或购买！");
            }
            //设置返回的课程id
            chapterInfoIndexDTO.setCourseId(courseEntity.getId());
            //设置返回的课程名称
            chapterInfoIndexDTO.setCourseName(courseEntity.getName());
            return chapterInfoIndexDTO;
        }
        return null;
    }

    @Override
    public Map<String, Object> chapterInfo(String chapterId) {
        if (StringUtils.isNotBlank(chapterId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("chapterId", chapterId);
            Map<String, Object> chapterMap = chapterRepository.findPageByNativeQueryFileds("select kczj.courseId, kc.name, zj.* from course kc left join course_chapter kczj on kc.id = kczj.courseId left join chapter zj on zj.id = kczj.chapterId WHERE zj.id=:chapterId",
                    map, Transformers.aliasToBean(HashMap.class), null, null);
            return chapterMap;
        }
        return null;
    }

    @Override
    public ChapterDTO updateChapter(ChapterDTO chapterDTO) {
        if (StringUtils.isNotBlank(chapterDTO.getId()) && StringUtils.isNotBlank(chapterDTO.getCourseId())) {
            ChapterEntity chapterEntity = chapterRepository.findById(chapterDTO.getId());
            if (chapterEntity != null) {
                BeanUtils.copyProperties(chapterDTO, chapterEntity);
                chapterEntity = chapterRepository.update(chapterEntity);

                // 保存到course_chapter表
                Map paramMap = new HashMap();
                paramMap.put("chapterId", chapterEntity.getId());
                paramMap.put("courseId", chapterDTO.getCourseId());
                String hql = "as v set v.courseId=:courseId where v.chapterId=:chapterId";
                chapterRepository.updateFileds(CourseChapterEntity.class, hql, paramMap, null);

                BeanUtils.copyProperties(chapterEntity, chapterDTO);
                return chapterDTO;
            }
        }
        return null;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        if (StringUtils.isNotBlank(chapterId)) {
            boolean chapter = chapterRepository.deleteById(chapterId);
            if (chapter) {
                return chapterRepository.delMiddleTable(CourseChapterEntity.class, "chapterId", chapterId, null, null);
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> chapterEntityList(String courseId) {
        if (StringUtils.isNotBlank(courseId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("courseId", courseId);
            return chapterRepository.findPageByNativeQueryFileds("select kczj.courseId, kc.name, zj.* from course kc left join course_chapter kczj on kc.id = kczj.courseId left join chapter zj on zj.id = kczj.chapterId WHERE kc.id=:courseId",
                    map, Transformers.aliasToBean(HashMap.class), null, null);
        } else {
            return chapterRepository.findPageByNativeQueryFileds("select kczj.courseId, kc.name, zj.* from chapter zj left join course_chapter kczj on zj.id = kczj.chapterId left join course kc on kc.id = kczj.courseId",
                    null, Transformers.aliasToBean(HashMap.class), null, null);
        }
    }

    public List<VideoEntity> videoEntityList(String chapterId) {
        //查询章节视频中间表
        List<ChapterVideoEntity> chapterVideoEntityList = chapterRepository.findByFiled(ChapterVideoEntity.class, "chapterId", chapterId);
        List list = new ArrayList();
        for (int i = 0; i < chapterVideoEntityList.size(); i++) {
            //查询视频详情
            VideoEntity videoEntity = chapterRepository.findById(VideoEntity.class, chapterVideoEntityList.get(i).getVideoId());
            list.add(videoEntity);
        }
        return list;
    }
}
